package com.centit.cxtj.controller;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.centit.airplanebaseinfo.po.AirplaneBaseinfo;
import com.centit.airplanebaseinfo.service.AirplaneBaseinfoManager;
import com.centit.cxtj.service.CxtjManager;
import com.centit.exchange.po.ExchangeRate;
import com.centit.exchange.service.ExchangeRateManager;
import com.centit.framework.common.ResponseMapData;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.core.controller.BaseController;
import com.centit.support.database.utils.PageDesc;
import com.centit.util.HttpRequest;
import com.centit.util.LayuiResultUtil;
import com.centit.util.excelUtil.ExportExcel;


@Controller
@RequestMapping("/cxtj")
public class CxtjDataController  extends BaseController  {
	private static final Log log = LogFactory.getLog(CxtjDataController.class);
	
	
	@Resource
	private CxtjManager cxtjMag;
	@Resource
	private ExchangeRateManager exchangeRateMag;
	@Resource
	private AirplaneBaseinfoManager airplaneBaseinfoManager;
	
	/**
	 * 	历年飞机引进情况
	 * @param field
	 * @param pageDesc
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getFjyjqlList",method = RequestMethod.GET)
    public void getFjyjqlList(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> searchColumn = convertSearchColumn(request); 
    	searchColumn.put("status", "2");
        JSONArray jsonArrayObjects = cxtjMag.getFjyjqlList( searchColumn, null);
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);
        LayuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
    }
	
	/**
	 *   	历年机队信息表   历年机型信息表   
	 * @param field
	 * @param pageDesc
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/lnjdxxb",method = RequestMethod.GET)
	public void lnjdxxb(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> searchColumn = convertSearchColumn(request); 
        JSONArray jsonArrayObjects = cxtjMag.lnjdxxb(searchColumn);
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);
        LayuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
    }
	
	/**
	 *   	在用飞机信息情况表
	 * @param field
	 * @param pageDesc
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/fjxxqk",method = RequestMethod.GET)
	public void fjxxqk(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> searchColumn = convertSearchColumn(request); 
        JSONArray jsonArrayObjects = cxtjMag.fjxxqk(searchColumn);
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);
        LayuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
    }
	
	/**
	 *   	在用飞机信息情况表 合计
	 * @param field
	 * @param pageDesc
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/fjxxqkhj",method = RequestMethod.GET)
	public void fjxxqkhj(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> searchColumn = convertSearchColumn(request); 
        JSONArray jsonArrayObjects = cxtjMag.fjxxqkhj(searchColumn);
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);
        LayuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
    }
	
	
	/**
	 * 	机龄分析
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getJlfxList",method = RequestMethod.GET)
	@ResponseBody
    public JSONArray getJlfxList(HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> searchColumn = convertSearchColumn(request); 
        return cxtjMag.getJlfxList(searchColumn);
    }
	
	/**
	 * 	飞机租赁性质分析
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getFjzlxzList",method = RequestMethod.GET)
	@ResponseBody
    public JSONArray getFjzlxzList(HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> searchColumn = convertSearchColumn(request); 
    	JSONArray jsonArrayObjects = cxtjMag.getFjzlxzList(searchColumn);
        return jsonArrayObjects;
    }
	
	
	/**
	 *  	首页顶部数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/homePageTopNum",method = RequestMethod.GET)
	@ResponseBody
    public JSONArray homePageTopNum(HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> searchColumn = convertSearchColumn(request); 
        return cxtjMag.homePageTopNum(searchColumn);
    }
	
	
	
	
	
	/**
	 *   	系统所有存在的机型列表接口
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/jxlist",method = RequestMethod.GET)
	@ResponseBody
    public JSONArray jxlist(HttpServletRequest request, HttpServletResponse response) {
        return cxtjMag.jxlist();
    }
	
	/**
	 * 	飞机型号分析
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/fjxhfx",method = RequestMethod.GET)
	@ResponseBody
    public JSONArray fjxhfx(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request); 
        return cxtjMag.lnjdxxb(searchColumn);
    }
	
	/**
	 * 	飞机引进分析--统计分析
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/fjyjfx",method = RequestMethod.GET)
	@ResponseBody
    public JSONArray fjyjfx(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request); 
        return cxtjMag.fjyjfx(searchColumn);
    }
	
	/**
	 * 	飞机数据测算  就是合同金额 和 汇率的对比
	 * @param field
	 * @param pageDesc
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/fjsjcsgl",method = RequestMethod.GET)
	public void fjsjcsgl(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request); 
		searchColumn.put("status", "2"); //2020年4月10日16:56:56  客户提出的这里只统计实际运营的
		if(searchColumn.containsKey("sign[]") && searchColumn.get("sign[]") != null) {
			searchColumn.put("signList", searchColumn.get("sign[]").toString().split(","));
		}
        JSONArray jsonArrayObjects = cxtjMag.fjsjcsgl(searchColumn);
        for (int i = 0; i < jsonArrayObjects.size(); i++) {
            JSONObject jsonObject = jsonArrayObjects.getJSONObject(i);
            if (StringUtils.isNotEmpty(jsonObject.getString("airZt"))) {
                jsonObject.put("airZt", CodeRepositoryUtil.getValue("AIRZT", jsonObject.getString("airZt")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("nature"))) {
                jsonObject.put("nature", CodeRepositoryUtil.getValue("AIRXZ", jsonObject.getString("nature")));
            }
        }  
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);
        LayuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
	}
	
	
	
	
	@RequestMapping(value = "/fjsjcsgl/down",method = RequestMethod.GET)
	public void fjsjcsglDown(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request);
		searchColumn.put("status", "2"); //2020年4月10日16:56:56  客户提出的这里只导出实际运营的
		if(searchColumn.containsKey("signList") && searchColumn.get("signList") != null && StringUtils.isNotBlank(searchColumn.get("signList").toString())) {
			searchColumn.put("signList", searchColumn.get("signList").toString().split(","));
		}
		JSONArray jsonArrayObjects = cxtjMag.fjsjcsgl(searchColumn);
        for (int i = 0; i < jsonArrayObjects.size(); i++) {
            JSONObject jsonObject = jsonArrayObjects.getJSONObject(i);
            if (StringUtils.isNotEmpty(jsonObject.getString("airZt"))) {
                jsonObject.put("airZt", CodeRepositoryUtil.getValue("AIRZT", jsonObject.getString("airZt")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("nature"))) {
                jsonObject.put("nature", CodeRepositoryUtil.getValue("AIRXZ", jsonObject.getString("nature")));
            }
        }  
        ExchangeRate ksExchangeRate = new ExchangeRate();
        ExchangeRate jsExchangeRate = new ExchangeRate();
        try {
        	ksExchangeRate = exchangeRateMag.getObjectById(searchColumn.get("starnf").toString());
        	jsExchangeRate = exchangeRateMag.getObjectById(searchColumn.get("endnf").toString());
        } catch (Exception e) {
			e.printStackTrace();
		}
        String[] headers = {"序号", "国籍标志和登记标志","航空器型号和制造人","飞机性质","飞机状态","合同金额","",""};
        String[] keys = {"count", "sign","airModel","nature","status","htMoney","qhl","hhl"};
        if(ksExchangeRate != null) {
        	headers[6] = ksExchangeRate.getFbDate()+"美元汇率："+(Double.valueOf(ksExchangeRate.getBankConversionPri())/100);
        }
        if(jsExchangeRate != null) {
        	headers[7] = jsExchangeRate.getFbDate()+"美元汇率："+(Double.valueOf(jsExchangeRate.getBankConversionPri())/100);
        }
        JSONArray jsonArray=new JSONArray();
        for (int i=0;i<headers.length;i++){
        	JSONObject jsonObject = new JSONObject();
            jsonObject.put("title",headers[i]);
            jsonObject.put("level","1");
            jsonObject.put("children","[]");
            jsonArray.add(jsonObject);
        }
        String fileName = "飞机数据测算管理";
        ExportExcel ex = new ExportExcel(fileName,fileName, jsonArray, jsonArrayObjects,keys,response);
        try {
			ex.export();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value = "/down",method = RequestMethod.GET)
	public void down(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request);
    	String type = (String)searchColumn.get("type");
    	if(type == null || "".equals(type)) {
    		type = "0";
    	}
    	JSONArray jsonArrayObjects = new JSONArray();
    	JSONArray jsonArrayObjectsTop = new JSONArray();
    	if("0".equals(type)) {
    	 	searchColumn.put("status", "2");
    		jsonArrayObjects = cxtjMag.getFjyjqlList( searchColumn, null);
    	} else if ("1".equals(type)) {
    		jsonArrayObjects = cxtjMag.fjxxqk(searchColumn);
    		jsonArrayObjectsTop = cxtjMag.fjxxqkhj(searchColumn);
    	} else if("2".equals(type)) {
    		jsonArrayObjects = cxtjMag.lnjdxxb(searchColumn);
    	}
    	JSONArray jslist = cxtjMag.jxlist();
    	String[] headers3 = new String[jslist.size()+2];
    	headers3[0] = "序号";
    	String[] keys3 = new String[jslist.size()+2];
    	keys3[0] = "count";
    	for (int i = 0; i < jslist.size(); i++) {
    		headers3[i+1] = jslist.getJSONObject(i).getString("airModel");
    		keys3[i+1] = jslist.getJSONObject(i).getString("airModel");
		}
    	headers3[jslist.size()+1]="年末在用飞机架数";
    	keys3[jslist.size()+1]="allNum";
    			
    	String[] headers1 = {"年份", "序号","机型","注册号","引进时间","备注"};
    	String[] headers2top = {"机型","数量","合计数量","平均机龄","更新日期"};
    	String[] headers2 = {"序号","机型","注册号","出厂时间","进江苏时间","机龄","性质","备注"};
    	String[] keys1 = new String[]{"nf","xh","jx","zch","yjsj","bz"};
    	String[] keys2Top = new String[]{"xh","num","hj","pjjl","gxrq"};
    	String[] keys2 = new String[]{"count","jx","zch","ccsj","yjsj","jl","xz","bz"};
        JSONArray jsonArray = extracted(type, headers1, headers2, headers3);
        
        JSONArray jsonArrayTop=new JSONArray();
        for (int i=0;i<headers2top.length;i++){
        	JSONObject jsonObject=new JSONObject();
            jsonObject.put("title",headers2top[i]);
            jsonObject.put("level","1");
            jsonObject.put("children","[]");
            jsonArrayTop.add(jsonObject);
        }
        
        try {
	        ExportExcel ex = null;
	        String filename = "";
	        if(type.equals("0")) {
	        	filename = "历年飞机引进情况";
	        	ex = new ExportExcel(filename,filename, jsonArray, jsonArrayObjects,keys1,response);
	        	ex.exportNoNumber();
	        } else if(type.equals("1")) {
	        	filename = "飞机信息情况";
	        	ex = new ExportExcel();
	        	ex.exportFjxxqk(filename,filename, jsonArray, jsonArrayObjects,keys2,jsonArrayTop, jsonArrayObjectsTop,keys2Top,response);
	        } else if(type.equals("2")) {
	        	filename = "历年机型信息表";
	        	ex = new ExportExcel(filename,filename, jsonArray, jsonArrayObjects,keys3,response);
	        	ex.export();
	        }
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	private JSONArray extracted(String type, String[] headers1, String[] headers2, String[] headers3) {
		JSONArray jsonArray=new JSONArray();
		if("0".equals(type)) {
			for (int i=0;i<headers1.length;i++){
				JSONObject jsonObject=new JSONObject();
                jsonObject.put("title",headers1[i]);
                jsonObject.put("level","1");
                jsonObject.put("children","[]");
                jsonArray.add(jsonObject);
			}
    	} else if ("1".equals(type)) {
    		for (int i=0;i<headers2.length;i++){
				JSONObject jsonObject=new JSONObject();
                jsonObject.put("title",headers2[i]);
                jsonObject.put("level","1");
                jsonObject.put("children","[]");
                jsonArray.add(jsonObject);
			}
    	} else if("2".equals(type)) {
    		for (int i=0;i<headers3.length;i++){
				JSONObject jsonObject=new JSONObject();
                jsonObject.put("title",headers3[i]);
                jsonObject.put("level","1");
                jsonObject.put("children","[]");
                jsonArray.add(jsonObject);
			}
    	}
		return jsonArray;	
	}

	/**
	 * 获取在用飞机接口
	 * @return
	 */
	@RequestMapping(value = "/getAllUseAirPlan",method= RequestMethod.GET)
	@ResponseBody
	public List<AirplaneBaseinfo> getAllUseAirPlan() {
		Map<String, Object> filterMap = new HashMap<String, Object>();
		filterMap.put("status", "2");
		return cxtjMag.listObjects(filterMap);
	}
	
	
	/**
	 *  数据报表中 所选中的列excel导出
	 * @param field
	 * @param pageDesc
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/airList/down",method = RequestMethod.POST)
	public void airListDown(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request);
    	String list = (String)searchColumn.get("list");
    	if(list == null || "".equals(list)) {
    		return;
    	}
    	JSONArray jsonArray = JSONArray.parseArray(list);
    	String[] header = new String[jsonArray.size()+1];
    	String[] keys = new String[jsonArray.size()+1];
    	header[0] = "序号";
    	keys[0] = "count";
    	for(int i = 0 ; i< jsonArray.size(); i++) {
    		JSONObject jsonObject = jsonArray.getJSONObject(i);
    		header[i+1] = jsonObject.getString("name");
    		if(jsonObject.getString("value").equals("gljh")) {
    			keys[i+1] = jsonObject.getString("gljhtext");
    		} else {
    			keys[i+1] = jsonObject.getString("value");
    		}
    	}
    	
    	Map<String, Object> map = new HashMap<>();
    	map.put("dataValid", "T");
    	map.put("status", "2");
    	JSONArray jsonArrayObjects = cxtjMag.listAirPlain(map);
    	for (int i = 0; i < jsonArrayObjects.size(); i++) {
            JSONObject jsonObject = jsonArrayObjects.getJSONObject(i);
            if (StringUtils.isNotEmpty(jsonObject.getString("airZt"))) {
                jsonObject.put("airZt", CodeRepositoryUtil.getValue("AIRZT", jsonObject.getString("airZt")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("nature"))) {
                jsonObject.put("nature", CodeRepositoryUtil.getValue("AIRXZ", jsonObject.getString("nature")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("zjbz"))) {
                jsonObject.put("zjbz", CodeRepositoryUtil.getValue("BZ", jsonObject.getString("zjbz")));
            }
            
            if (StringUtils.isNotEmpty(jsonObject.getString("ht"))) {
                jsonObject.put("ht", getFileName(jsonObject.getString("ht")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("gjz"))) {
                jsonObject.put("gjz", getFileName(jsonObject.getString("gjz")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("zjbz"))) {
                jsonObject.put("dtz", getFileName(jsonObject.getString("dtz")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("zjbz"))) {
                jsonObject.put("shz", getFileName(jsonObject.getString("shz")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("pw"))) {
                jsonObject.put("pw", getFileName(jsonObject.getString("pw")));
            }
            
        }  
    	JSONArray jsonArrayHeader=new JSONArray();
        for (int i=0;i<header.length;i++){
        	JSONObject jsonObject=new JSONObject();
            jsonObject.put("title",header[i]);
            jsonObject.put("level","1");
            jsonObject.put("children","[]");
            jsonArrayHeader.add(jsonObject);
        }
        try {
	        String filename =  "数据报表";
	        ExportExcel ex = new ExportExcel(filename,filename, jsonArrayHeader, jsonArrayObjects,keys,response);
        	ex.export();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * 数据报表中 所选中的列 所包含的附件压缩导出
	 * @param field
	 * @param pageDesc
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/airList/down/fj",method = RequestMethod.POST)
	public void airListDownFj(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> searchColumn = convertSearchColumn(request);
    	String list = (String)searchColumn.get("list");
    	if(list == null || "".equals(list)) {
    		return;
    	}
    	JSONArray jsonArray = JSONArray.parseArray(list);
    	Map<String, Object> map = new HashMap<>();
    	map.put("dataValid", "T");
    	map.put("status", "2");
    	JSONArray jsonArrayObjects = cxtjMag.listAirPlain(map);
    	cxtjMag.downAirListFj(jsonArray, jsonArrayObjects,response);
	}
	
	
	@RequestMapping(value = "/airList",method = RequestMethod.GET)
    public void listAirPian(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> searchColumn = convertSearchColumn(request); 
    	searchColumn.put("dataValid", "T");
    	searchColumn.put("status", "2");
        JSONArray jsonArrayObjects = cxtjMag.listAirPlain(searchColumn);
        for (int i = 0; i < jsonArrayObjects.size(); i++) {
            JSONObject jsonObject = jsonArrayObjects.getJSONObject(i);
            if (StringUtils.isNotEmpty(jsonObject.getString("airZt"))) {
                jsonObject.put("airZt", CodeRepositoryUtil.getValue("AIRZT", jsonObject.getString("airZt")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("nature"))) {
                jsonObject.put("nature", CodeRepositoryUtil.getValue("AIRXZ", jsonObject.getString("nature")));
            }
            if (StringUtils.isNotEmpty(jsonObject.getString("zjbz"))) {
                jsonObject.put("zjbz", CodeRepositoryUtil.getValue("BZ", jsonObject.getString("zjbz")));
            }
            if (StringUtils.isEmpty(jsonObject.getString("gljh"))||StringUtils.isBlank(jsonObject.getString("gljh"))) {
                jsonObject.put("gljh", "无");
                jsonObject.put("gljhtext", "无");
            }
        }  
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);
        LayuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
    }
	
	
	private String getFileName(String path) {
		String filename = "";
		if(StringUtils.isNotBlank(path)) {
			//可能是多个文件 id用逗号隔开
			String[] fileIds = path.split(",");
			for(int i = 0 ; i < fileIds.length ; i++) {
				String result = HttpRequest.sendRestGet(CodeRepositoryUtil.getSysConfigValue("uploaderpath")+"/service/files",fileIds[i]);
	            JSONObject jsonObject = JSONObject.parseObject(result);
	            filename += ((JSONObject)jsonObject.get("data")).get("fileName").toString();
			}
		}
		return filename;
	}
}
